package com.qfmy.webapp.service.impl.common;

import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.common.BookSelf;
import com.qfmy.model.entity.novel.History;
import com.qfmy.model.entity.novel.Novel;
import com.qfmy.model.enums.NovelStatus;
import com.qfmy.model.vo.common.BookSelfVo;
import com.qfmy.model.vo.novel.NovelVo;
import com.qfmy.webapp.mapper.common.BookSelfMapper;
import com.qfmy.webapp.mapper.novel.ChapterMapper;
import com.qfmy.webapp.mapper.novel.HistoryMapper;
import com.qfmy.webapp.mapper.novel.NovelMapper;
import com.qfmy.webapp.service.common.BookSelfService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * @author 清风明月
 * @Package com.qfmy.web.app.service.impl.novel
 * @date 2025/10/31
 * @description 小说书架
 * */
@Slf4j
@Service
public class BookSelfServiceImpl implements BookSelfService {
    /**
     * 注入mapper
     */
    @Autowired
    private BookSelfMapper bookSelfMapper;

    /**
     * 注入小说mapper
     */
    @Autowired
    private NovelMapper novelMapper;

    /**
     * 注入浏览历史
     */
    @Autowired
    private HistoryMapper historyMapper;

    /**
     * 注入章节表
     */
    @Autowired
    private ChapterMapper chapterMapper;

    /**
     * 添加小说
     * @param novelId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addNovelSelf(Integer novelId) {
        //获取用户id
        Long userId = getUserId();
        //根据用户id和小说id查询是否添加过了
        BookSelf bookSelf = bookSelfMapper.getBookSelf(userId, novelId);
        if(bookSelf != null)
        {
            //判断是不是逻辑删除了
            if(bookSelf.getIsDelete() == 1)
            {
                bookSelfMapper.updateBookSelf(bookSelf.getId());
                return;
            }else{
                //抛出异常
                throw new BaseException(ResultCodeEnum.NOVEL_SELF_EXIST);
            }
        }
        //创建novelSelf对象
        bookSelf = new BookSelf();
        //设置属性
        bookSelf.setUserId(userId);
        bookSelf.setNovelId(novelId);
        bookSelfMapper.addNovelSelf(bookSelf);
    }

    /**
     * 判断是否在书架中
     * @param novelId
     * @return
     */
    @Override
    public Boolean isInNovelSelf(Integer novelId) {
        //获取用户id
        Long userId = getUserId();
        return bookSelfMapper.isInBookSelf(novelId, userId);
    }

    /**
     * 获取用户书架
     * @return
     */
    @Override
    public List<BookSelfVo> getNovelSelf() {
        //获取用户id
        Long userId = getUserId();
        if (userId == null || userId < 0) {
            return Collections.emptyList();
        }

        //获取用户书架
        List<BookSelf> bookSelfList = bookSelfMapper.getAllBookSelf(userId);

        // 处理小说流
        return bookSelfList.parallelStream()
                .filter(bookSelf -> bookSelf.getNovelId() != null)
                .map(bookSelf -> {
                    Integer novelId = bookSelf.getNovelId();
                    Novel novel = novelMapper.selectById(novelId);
                    NovelVo novelVo = new NovelVo();

                    if (novel != null) {
                        BeanUtils.copyProperties(novel, novelVo);
                        novelVo.setStatus(NovelStatus.getNameByCode(novel.getStatus()));

                        // 获取最新章节名称
                        if (novel.getLastChapterId() != null) {
                            String lastChapterName = chapterMapper.getChapterByIndex(novel.getLastChapterId(), novelId);
                            novelVo.setLastChapterName(lastChapterName);
                        }
                    }

                    // 查询浏览历史，设置当前阅读章节
                    History history = historyMapper.selectHistory(userId, novelId);
                    if (history != null) {
                        novelVo.setChapterIndex(history.getChapterIndex());
                    }

                    BookSelfVo bookSelfVo = new BookSelfVo();
                    bookSelfVo.setNovelVo(novelVo);
                    bookSelfVo.setId(bookSelf.getId());
                    bookSelfVo.setUpdateTime(bookSelf.getUpdateTime());
                    return bookSelfVo;
                })
                .toList();
    }

    /**
     * 删除书架
     * @param id
     */
    @Override
    public void deleteNovelSelf(Integer[] id) {
        bookSelfMapper.deleteBookSelf(id);
    }

    /**
     * 获取小说数量
     * @param novelId
     * @return
     */
    @Override
    public Integer countNovelSelf(Integer novelId) {
        return bookSelfMapper.countNovels(novelId);
    }

    /**
     * 获取所有逻辑删除的小说书架
     * @return
     */
    @Override
    public List<BookSelfVo> getAllDeleted() {
        Long userId = getUserId();
        if (userId == null || userId < 0){
            return Collections.emptyList();
        }

        // 获取所有逻辑删除的书架记录
        List<BookSelf> bookSelfList = bookSelfMapper.getAllDeleted(userId);

        // 仅处理小说相关记录
        return bookSelfList.stream()
                .filter(bookSelf -> bookSelf.getNovelId() != null)
                .map(bookSelf -> {
                    Integer novelId = bookSelf.getNovelId();
                    Novel novel = novelMapper.selectById(novelId);
                    NovelVo novelVo = new NovelVo();

                    if (novel != null) {
                        BeanUtils.copyProperties(novel, novelVo);
                    }

                    BookSelfVo bookSelfVo = new BookSelfVo();
                    bookSelfVo.setNovelVo(novelVo);
                    bookSelfVo.setId(bookSelf.getId());
                    bookSelfVo.setUpdateTime(bookSelf.getUpdateTime());
                    return bookSelfVo;
                })
                .sorted((vo1, vo2) -> {
                    if (vo1.getUpdateTime() == null && vo2.getUpdateTime() == null) return 0;
                    if (vo1.getUpdateTime() == null) return 1;
                    if (vo2.getUpdateTime() == null) return -1;
                    return vo2.getUpdateTime().compareTo(vo1.getUpdateTime());
                })
                .toList();
    }

    /**
     * 恢复书籍
     * @param id
     */
    @Override
    public void findNovel(Integer id) {
        Long userId = getUserId();
        if (userId == null || userId < 0){
            throw new BaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }
        bookSelfMapper.findNovel(id, userId);
    }

    /**
     * 获取用户id
     */
    @Nullable
    @Contract(pure = true)
    private Long getUserId() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        if (loginUser == null) {
            throw new BaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }
        return loginUser.getUserId();
    }
}